import { useState } from "react";
import type { ChangeEvent } from "react";

const resolveValue = <T,>(e: T | ChangeEvent<{ value: T }>): T => {
    // 如果是事件对象，返回其 value
    if (
        e &&
        typeof e === 'object' &&
        'target' in e &&
        e.target &&
        typeof e.target === 'object'
    ) {
        // 安全访问 value
        const value = (e.target as { value?: T }).value;
        if (value !== undefined) {
            return value;
        }
    }
    // 否则，e 就是直接传入的值
    return e as T;
};

export default function useModel<T>(initialValue: T) {
    const [state, setState] = useState<T>(initialValue);

    const bindValue = {
        value: state,
        onChange: (e: T | ChangeEvent<{ value: T }>) => setState(resolveValue(e)),
        onInput:  (e: T | ChangeEvent<{ value: T }>) => setState(resolveValue(e)),
    };

    return [state, bindValue, setState] as const;
}
